<script setup>

import {getCurrentInstance, ref} from "vue";
import {listSysMenuAll} from "@/api/system/menu";
import {addRoleMenu, getRoleMenu, updateRoleMenu} from "@/api/system/rolemenu";

const {proxy} = getCurrentInstance();
const emit = defineEmits(['success'])
const modalRef = ref();
const formType = ref('create');
const allMenuList = ref([]);
const treeProps = ref({
  checkStrictly: false,
})
const selectedMenuIds = ref([]);
const formData = ref({
  id: undefined,
  roleId: undefined,
  menuIds: ''
});

const open = async (roleId, type = 'create') => {
  formType.value = type;
  formData.value.roleId = roleId
  getRoleMenu(roleId).then(resp => {
    if (resp.data) {
      formData.value = {
        ...resp.data
      }
      selectedMenuIds.value = resp?.data?.menuIds
          .split(',')
          .filter(item => item !== '')
          .map(item => Number(item)) ?? []
    }
  })
  modalRef.value.handleOpen();
  getSysMenuAll();
}

const handleSubmit = async () => {
  let selectedMenuId = getSelectedMenuId();
  formData.value.menuIds = selectedMenuId.length === 0 ? '' : selectedMenuId.join(',')
  if (formData.value.id !== undefined) {
    await updateRoleMenu(formData.value);
    proxy.$modal.okNotify('角色分配成功');
  } else {
    await addRoleMenu(formData.value);
    proxy.$modal.okNotify('角色分配成功');
  }
  resetForm();
  modalRef.value.handleClose();
  emit('success')
}

const getSelectedMenuId = () => {
  const selectedMenuIds = [];

  // 递归函数来收集所有层级的选中menuId
  const collectSelectedMenuIds = (menus) => {
    menus.forEach(menu => {
      // 如果当前菜单被选中，收集其ID
      if (menu.selected) {
        selectedMenuIds.push(menu.menuId);
      }

      // 收集选中的权限的menuId
      if (menu.perms?.length) {
        menu.perms.forEach(perm => {
          if (perm.selected) {
            selectedMenuIds.push(perm.menuId);
          }
        });
      }

      // 如果有子菜单，递归处理
      if (menu.children?.length) {
        collectSelectedMenuIds(menu.children);
      }
    });
  };

  // 开始收集
  collectSelectedMenuIds(allMenuList.value);
  return selectedMenuIds;
}

const getSysMenuAll = () => {
  listSysMenuAll().then(resp => {
    // 递归处理菜单树
    const processMenuTree = (menuList) => {
      return menuList.map(menu => ({
        ...menu,
        selected: selectedMenuIds.value.indexOf(menu.menuId) !== -1,
        perms: menu.perms?.map(perm => ({
          ...perm,
          selected: selectedMenuIds.value.indexOf(perm.menuId) !== -1
        })) || [],
        // 递归处理子菜单
        children: menu.children ? processMenuTree(menu.children) : []
      }));
    };
    // 处理整个菜单树
    allMenuList.value = processMenuTree(resp.data);
  });
}

const resetForm = () => {
  formData.value = {
    roleId: undefined,
    menuIds: ''
  }
}

defineExpose({
  open
})
</script>

<template>
  <dialog-form ref="modalRef" modalTitle="分配角色" modalWidth="1200px"
               @submit="handleSubmit">
    <a-table
        :data-source="allMenuList"
        :tree-props="treeProps"
        row-key="menuId"
        default-expand-all>
      <a-table-column data-index="menuName" title="菜单名称">
        <template #default="{record}">
          <a-checkbox v-model:checked="record.selected">{{ record.menuName }}</a-checkbox>
        </template>
      </a-table-column>
      <a-table-column data-index="perms" title="操作权限">
        <template #default="{record}">
          <a-checkbox v-for="item in record.perms"
                       :key="item.menuName"
                       v-model:checked="item.selected"
                       :label="item.menuName">
            {{ item.menuName }}
          </a-checkbox>
        </template>
      </a-table-column>
    </a-table>
  </dialog-form>
</template>

<style scoped lang="scss">

</style>
